const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const _ = db.command
const $ = db.command.aggregate
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  switch (event.op) {
    case 'getLottery':
      return getLottery();
      break;
    case 'buyLottery':
      return buyLottery();
      break;
    case 'buyHistory':
      return buyHistory();
      break;
  }


  async function getLottery() {
    let preday = new Date(Date.now() - (16 * 60 * 60 * 1000))
    let buydayStr = preday.getFullYear().toString() + (preday.getMonth() + 1).toString() + preday.getDate().toString();
    let res = await db.collection("Lottery")
      .where({
        buyday: buydayStr
      }).get()
    let res2 = await db.collection("LotteryBuyRecord")
      .where({
        buyday: buydayStr,
        _openid: wxContext.OPENID
      }).get()

    return {
      winData: res.data[0],
      buyData: res2.data,
    }
  }

  async function buyLottery() {
    let today = new Date(Date.now() + (8 * 60 * 60 * 1000))
    let buydayStr = today.getFullYear().toString() + (today.getMonth() + 1).toString() + today.getDate().toString();
    await db.collection("LotteryBuyRecord").add({
      data: {
        buyday: buydayStr,
        balls: {
          redballs: arraySort(event.data.redballs),
          blueball: event.data.blueball,
        },
        _openid: wxContext.OPENID,
        createTime: db.serverDate()
      }
    })
    await db.collection('User').where({
      _openid: wxContext.OPENID
    }).update({
      data: {
        gold: _.inc(-2)
      }
    })
    return 'buyok'

  }
  async function buyHistory() {
    let res = await db.collection('LotteryBuyRecord').aggregate()
      .match({
        _openid: wxContext.OPENID
      })
      .group({
        _id: '$buyday',
        list: $.push({
          blueball: '$balls.blueball',
          redballs: '$balls.redballs',
          awardRank: '$awardRank'
        }),
      }).project({
        buyday: '$_id.buyday',
        list: 1,
      })
      .sort({_id:-1})
      .end()
    return res.list
  }

  function arraySort(a) {
    for (let i = 0; i < a.length; i++) {
      for (let j = i; j > 0 && a[j] < a[j - 1]; j--) {
        var temp = a[j]
        a[j] = a[j - 1]
        a[j - 1] = temp
      }
    }
    return a
  }
}